<template>
  <a-table :columns="columns" :data-source="data.tableData" :pagination="pagination">
    <template v-slot:name="{ text }">
      <a>{{ text }}</a>
    </template>
    <template v-slot:action="{ record }">
      <span @click.stop="">
        <a @click="handleEdit(record.key)">Edit</a>
        <a-divider type="vertical" />
        <a-popconfirm ok-text="Yes" cancel-text="No" @confirm="handleDelete(record.key)"
          title="Are you sure delete this category?">
          <a href="javascript:;">Delete</a>
        </a-popconfirm>
      </span>
    </template>
  </a-table>
</template>
<script>
import { onMounted, reactive, ref, getCurrentInstance } from 'vue'
import { ResourceGetAll, ResourceDelete } from '../ceshi.js'
import router from '../router'
const columns = [
  {
    title: 'Id',
    dataIndex: '_id',
    key: '_id',
    slots: { title: 'customTitle' }
  },
  {
    title: '分类名称',
    dataIndex: 'name',
    key: 'name',
    slots: { title: 'customTitle' }
  },
  {
    title: '父级分类',
    dataIndex: 'parent.name',
    key: 'parent.name',
    slots: { title: 'customTitle' }
  },
  {
    title: '操作',
    key: 'action',
    slots: { title: 'customTitle', customRender: 'action' }
  }
]
export default {
  setup () {
    const data = reactive({
      tableData: []
    })
    const pagination = ref({
      defaultPageSize: 8,
      showTotal: total => `共 ${data.tableData.length} 条数据`,
      // showSizeChanger: true,
      // pageSizeOptions: ['5', '10', '15', '20'],
      onShowSizeChange: (current, pageSize) => {
        this.pageSize = pageSize
      }
    })
    onMounted(async () => {
      const res = await ResourceGetAll('categories')
      console.log(res.data)
      data.tableData = res.data
      // console.log(toRaw(data.tableData))
    })
    // 组件方法
    function handleEdit (id) {
      router.push(`/category/edit/${id}`)
    }
    const instance = getCurrentInstance()
    function handleDelete (id) {
      ResourceDelete('categories', id)
        .then(async () => {
          instance.ctx.$message.success('删除成功！')
          const res = await ResourceGetAll('categories')
          data.tableData = res.data
        })
        .catch(() => {
          instance.ctx.$message.error('删除失败！')
        })
    }
    return { data, handleEdit, pagination, handleDelete }
  },
  data () {
    return {
      columns
    }
  }
}
</script>

<style lang="scss" scoped></style>
